import ELNode from './type/ELNode';

export class ELStack {
    private stack: ELNode[] = [];
    private ebpStack: number[] = [];


    private peek(data: any[]) {
        return data[data.length - 1];
    }

    public pop(): ELNode {
        return this.stack.pop()!;
    }

    public push(item: ELNode) {
        this.stack.push(item);
    }

    public clear() {
        this.stack = [];
    }

    public resolve(): ELNode {
        const ebp: number = this.peek(this.ebpStack);
        const typeNode: ELNode = this.stack[ebp + 1];

        for (let i = ebp + 2; i < this.stack.length; i++) {
            const elNode: ELNode = this.stack[i];
            typeNode.addChild(elNode);
        }
        return typeNode;
    }

    /**
     * @return 下一次分析的开始节点
     */
    public quit() {
        const typeNode: ELNode = this.resolve();
        const endPoint: ELNode = this.stack[this.peek(this.ebpStack)];
        while (this.stack.length > this.peek(this.ebpStack)) {
            this.stack.pop();
        }
        this.stack.push(typeNode);
        this.ebpStack.pop();

        return endPoint;
    }

    public create() {
        this.ebpStack.push(this.stack.length);

        //endpoint占位符
        this.stack.push(new ELNode());
    }

    public addEndPoint(elNode: ELNode) {
        this.stack[this.peek(this.ebpStack)] = elNode;
    }
}